package messages;

import javax.crypto.SecretKey;

import org.bouncycastle.crypto.CryptoException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import security.crypto.SimmEncryption;
import utils.XmlSerializationUtils;

public class SecChannelChallengeMessage implements Convertible {
	
	private static final long serialVersionUID = 1L;
	private String _cipheredChallenge;
	
	public SecChannelChallengeMessage(){
	}
	
	public SecChannelChallengeMessage(Integer challenge, SecretKey sessionKey){		
		_cipheredChallenge = SimmEncryption.cipherString(challenge.toString(), sessionKey);
	}
	
	public SecChannelChallengeMessage(Integer clientChallenge, Integer serverChallenge, SecretKey sessionKey){
		Integer challenge = clientChallenge + serverChallenge;
		
		_cipheredChallenge = SimmEncryption.cipherString(challenge.toString(), sessionKey);
	}
	
	public int getChallenge(int originalCliChallenge, SecretKey sessionKey) throws CryptoException{
		String challengeString = SimmEncryption.decipherString(_cipheredChallenge, sessionKey);
		
		if(challengeString != null){
			int receivedChallenge = Integer.parseInt(challengeString);		
			return receivedChallenge - originalCliChallenge;
		}else 
			throw new CryptoException();
		
		
	}
	
	public int getChallenge(SecretKey sessionKey) throws CryptoException{
		String challengeString = SimmEncryption.decipherString(_cipheredChallenge, sessionKey);
		
		if(challengeString != null)
			return Integer.parseInt(challengeString);
		else 
			throw new CryptoException();
	}

	public Element convertToCanonic(Document doc) {
		Element el = doc.createElement("SecChannelChallengeMessage");

		if (_cipheredChallenge != null) {
			Element childEl = doc.createElement("CipheredChallenge");
			childEl.setTextContent(_cipheredChallenge);
			el.appendChild(childEl);
		}
		
		return el;
	}

	public Object convertFromCanonic(Element el) {
		this._cipheredChallenge = XmlSerializationUtils.getTextValue(el, "CipheredChallenge");
		return this;
	}
}
